package Netzwerkprogrammierung.g1.Sockets;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

public class UDPClient {


	public static void main(String[] args) throws IOException {

		Scanner s = new Scanner(System.in);
		
		System.out.println("Bitte einen String eingeben: ");
		
		String toSend = s.nextLine();
		
		DatagramSocket socket = new DatagramSocket();
		
		byte[] sendData = toSend.getBytes();
		
		InetAddress address = InetAddress.getByName("localhost");
		
		DatagramPacket packetToSend = 
				new DatagramPacket(sendData, sendData.length, address, 1234);
		
		socket.send(packetToSend);
		
		byte[] answerData = new byte[1024];
		
		DatagramPacket answer = new DatagramPacket(answerData,answerData.length);
		
		socket.receive(answer);
		
		String answerAsString = new String(answer.getData());
		
		String trimmedString = "";
		for(char c:answerAsString.toCharArray()){
			if(c != 0){
				trimmedString += c;
			}
		}
		
		socket.close();
		
		System.out.println("Answer from Server:"+ trimmedString);
		
		

	}

}
